package com.ly.test.controller;

import com.ly.test.params.GetUserParameter;
import com.ly.test.params.UploadParameter;
import com.ly.test.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author liuyi
 * @date 2017/01/16 15:09
 */
@RestController
//@Controller
@RequestMapping("/other")
public class OtherController {

    private final Logger logger = LoggerFactory.getLogger(OtherController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("")
    public String getUserName(GetUserParameter param){
        return userService.getUserById(param.getId()).getName();
    }

    @RequestMapping(value = "/upload")
    public String upload(UploadParameter param){
        MultipartFile file = param.getFile();
        logger.info(file==null?"file null":file.getOriginalFilename());
        logger.info(param.getParam2()==null?"param2 null":param.getParam2());
        return "1";
    }

    @RequestMapping(value ="/upload2", method= RequestMethod.POST)
    @ResponseBody
    public String upload2(@RequestParam("file") MultipartFile file){
        logger.info(file==null?"file null":file.getOriginalFilename());
        if (file != null && !file.isEmpty()) {
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                out.write(file.getBytes());
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            return "上传成功";
        } else {
            return "上传失败，因为文件是空的.";
        }
    }
}
